import fetch from '../fetch.js'
import request from 'request'
import conf from '../../../config.json'
import InformType from './InformType.js'
import ReplyOptType from './ReplyOptType.js'
import redisShare from '../redis.js'

const config = {
	prefix: conf.ptime.urlPrefix,
	getUserWithToken: '/api/user',
	getUserWithId: '/api/user',
	sendInform: '/api/inform/send',
	getAppUser: '/api/app/{app_id}/user',
	getAllApp: '/api/app',
	getCommentCount: '/api/comment/count',
	getComment: '/api/comment'
};

const headers = {
	'ptimeauth': '5a350362534f8a12d148743d26faa21d',
	'clientdate': '1398250549123',
	'user-agent': 'PTime.Dynamic/1.0'
};

const api = {
	getUserWithToken: async function (token) {
		if (!token) return null
		let userString = await redisShare.get(token)
		let user
		if (userString) {
			user = JSON.parse(userString)
		} else {
			const res = await fetch.request({
				method: 'get',
				url: config.prefix + config.getUserWithToken,
				headers: headers,
				qs: {token: token}
			});
			const resObject = JSON.parse(res.body)
			if (resObject.error) return null
			user = resObject.result
			if (!user) return null
			await redisShare.set(token, JSON.stringify(user))
			redisShare.expire(token, 60*5)
		}
		return user
	},
	getUserWithId: async function (userId) {
		const res = await fetch.request({
			method: 'get',
			url: `${config.prefix}${config.getUserWithId}/${userId}`,
			headers: headers,
		});
		return JSON.parse(res.body).result
	},
	getAllApp: async function () {
		const res = await fetch.request({
			method: 'get',
			url: `${config.prefix}${config.getAllApp}`,
			headers: headers,
		});
		return JSON.parse(res.body).result
	},
	getCommentCount: async function (commentids, userId) {
		const res = await fetch.request({
			method: 'get',
			url: `${conf.commentUrlPrefix}${config.getCommentCount}`,
			headers: headers,
			qs: {
				object: 'dynamic',
				object_ids: commentids.join(','),
				app_id: conf.appId,
				user_id: userId
			}
		})
		return JSON.parse(res.body).result
	},
	sendInformAsync: function (inform) {
		request({
			method: 'post',
			url: config.prefix + config.sendInform,
			headers: headers,
			body: {
				title: inform.title,
				content: null,
				app_id: conf.appId,
				set_id: conf.setId,
				sender_id: 1,
				close_trigger_type: null,
				close_trigger_value: null,
				final_close_time: null,
				users: inform.users,
				is_notcare: 1,
				methods: [
					{
						method_id: 1,
						tpl_id: null,
						trigger_type: null,
						trigger_value: null
					}
				],
				reply_opts: inform.replyOpts
			},
			json: true
		}, (error, res, body) => {
			if (error) {
				console.log(`通知发送失败`)
				console.dir(error)
				console.dir(body)
			}
			console.log(`通知发送结果:`)
			console.dir(body)
		});
	}, 
	sendCommentRelatedInform: sendCommentRelatedInform,
	getCommentInfo: async (commentId) => {
		const res = await fetch.request({
			method: 'get',
			url: `${conf.commentUrlPrefix}${config.getComment}/${commentId}`,
			headers: headers
		})
		return JSON.parse(res.body).result
	}
}

/**
 * 发送评论相关的通知
 * @param  {[type]} title 标题
 * @param  {[type]} users 用户列表
 * @return {[type]}       
 */
function sendCommentRelatedInform (title, users) {
	let replyOpt = new ReplyOptType('知道了')
	let inform = new InformType(title, users, [replyOpt])
	api.sendInformAsync(inform)
}

export default api